package com.yunliuchain.examination.system.service.impl;


import com.yunliuchain.examination.common.enums.SnType;
import com.yunliuchain.examination.common.service.impl.BaseServiceImpl;
import com.yunliuchain.examination.system.dao.SerialNumberDao;
import com.yunliuchain.examination.system.entity.SerialNumber;
import com.yunliuchain.examination.system.service.SerialNumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**<p>Title:系统编号表 服务实现类 </p>
 * <p>Description: </p>
 * <p>作者：zzc</p>
 * <p>日期：2018-05-16 15:56:49</p>
 * <p>版本：1.0</p>
 */
@Service
public class SerialNumberServiceImpl extends BaseServiceImpl<SerialNumber,Long> implements SerialNumberService {

    @Autowired
	private SerialNumberDao serialNumberDao;

    private static final int SEQUENCE_LENGTH= 6;

    @Override
    @Transactional(readOnly=false)
    public synchronized String getSnByType(SnType type) {
        SerialNumber serialNumber = serialNumberDao.getByType(type.getName());

        if(serialNumber == null){
            serialNumber = new SerialNumber(type.getName(),1l);
            serialNumberDao.add(serialNumber);
        }else 	if((serialNumber.getSn() + 1) > Long.MAX_VALUE ){
            throw new RuntimeException("编号已超出最大值");
        }else {
            serialNumber.setSn(serialNumber.getSn() + 1);
            serialNumberDao.update(serialNumber);
        }

        String valStr = ""+serialNumber.getSn();
        String newValStr = ""+serialNumber.getSn();
        if(valStr.length()<=SEQUENCE_LENGTH){
            for(int i=0;i<(SEQUENCE_LENGTH-valStr.length());i++){
                newValStr = "0" + newValStr;
            }
        }
        return type.getName() + newValStr;
    }
}
